package com.qidian.k12.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 戴着假发的程序
 */
public class ObjectTools {
    /**
     * 对象转map
     * @param obj
     * @return
     */
    public static Map object2map(Object obj){
        Map map = new HashMap();
        Class clazz = null;
        while(true){
            if (clazz == null)
                clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields){
                String name = field.getName();
                // 准备get方法
                String methodName = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                try {
                    Method getMethod = clazz.getMethod(methodName);
                    if(getMethod!=null) {
                        map.put(name, getMethod.invoke(obj));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //取出父类的class对象
            clazz = clazz.getSuperclass();
            if(clazz == Object.class){// 如果是Object就结束
                break;
            }
        }
        return map;
    }
}
